﻿using System;
using System.Net;
using System.Threading.Tasks;
using Common.Entitys.CommonLogs;
using MQTTnet;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;


namespace Common.Utils.MqttHelp
{
    /// <summary>
    /// Mqtt服务器帮助类
    /// </summary>
    public class MqttServerHelp
    {
        private MqttServer mqttServer = null;

        public MqttServerHelp()
        {

        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="ip"></param>
        public async Task Init(string ip = "192.168.1.16", int port = 8086)
        {
           await Validating_Connections(ip, port);
        }

        public async Task Validating_Connections(string ip, int port)
        {
            var optionsBuilder = new MqttServerOptionsBuilder()
                    .WithEncryptedEndpointBoundIPAddress(IPAddress.Parse(ip)).WithDefaultEndpointPort(8086).WithConnectionValidator(
                        p =>
                        {
                            //p.ReasonCode = MqttConnectReasonCode.Success;
                            //return;
                            if (p.ClientId == "TableProject")
                            {
                                //平板
                                if (p.Username != "Zane" || p.Password != "123456")
                                {
                                    p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                                    return;
                                }
                                else
                                {
                                    p.ReasonCode = MqttConnectReasonCode.Success;
                                    return;
                                }
                            }
                            else if (p.ClientId == "PaintRobot")
                            {
                                //喷涂软件
                                if (p.Username != "Zane" || p.Password != "123456")
                                {
                                    p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                                    return;
                                }
                                else
                                {
                                    p.ReasonCode = MqttConnectReasonCode.Success;
                                    return;
                                }
                            }
                            p.ReasonCode = MqttConnectReasonCode.Success;
                            return;
                        }
                        ).WithSubscriptionInterceptor(
                        c =>
                        {
                            c.AcceptSubscription = true;
                        }).WithApplicationMessageInterceptor(
                        c =>
                        {
                            c.AcceptPublish = true;
                        });

            mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
            mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(OnMqttServerStarted);
            mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(OnMqttServerStopped);

            mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
            mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
            mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(OnMqttServerClientSubscribedTopic);
            mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(OnMqttServerClientUnsubscribedTopic);
            mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMqttServer_ApplicationMessageReceived);

            await mqttServer.StartAsync(optionsBuilder.Build());

        }



        private void OnMqttServerStarted(EventArgs obj)
        {

        }

        private void OnMqttServerStopped(EventArgs obj)
        {
        }

        private void OnMqttServerClientConnected(MqttServerClientConnectedEventArgs e)
        {
            LogHelp.AddLog<InitLogEntity>($"客户端[{e.ClientId}]已连接，协议版本：{e.ProtocolVersion}");
        }
        private void OnMqttServerClientDisconnected(MqttServerClientDisconnectedEventArgs e)
        {
            LogHelp.AddLog<InitLogEntity>($"客户端[{e.ClientId}]已断开连接！");
        }

        private void OnMqttServerClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs obj)
        {
        }

        private void OnMqttServerClientUnsubscribedTopic(MqttServerClientUnsubscribedTopicEventArgs obj)
        {
        }

        private void OnMqttServer_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs obj)
        {
        }




    }
}
